package com.haiyi.software.app.basic;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.haiyi.software.app.MainApplication;
import com.haiyi.software.app.R;
import com.haiyi.software.entity.BeanLoginResultBody;
import com.haiyi.software.entity.UserInfo;
import com.haiyi.software.mycontrols.SoundMeter;
import com.haiyi.software.tools.L;
import com.haiyi.software.tools.MyTools;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;

public abstract class HiChatVoiceBasic extends HiChatActivityBasic {

	protected LinearLayout del_re;

	protected ImageView volume;

	protected View rcChat_popup;

	protected LinearLayout voice_rcd_hint_rcding, voice_rcd_hint_loading,
			voice_rcd_hint_tooshort;

	private Handler mHandler = new Handler();

	private boolean isShosrt = false;

	protected ImageView img1, sc_img1;

	private long startVoiceT, endVoiceT;

	private String voiceName;

	protected SoundMeter mSensor;

	private boolean isLongClick = false;

	protected TextView btn_voice;

	protected Long voiceLong;

	private File uploadFile;

	private static final int POLL_INTERVAL = 300;

	private UserInfo myInfo;

	protected JsonElement jsonReturn = null;

	protected abstract void UploadVoiceSuccess(int voicetime);

	protected String voicePath;

	private int time;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);

		myInfo = MainApplication.getInstance().getMineUserInfo();
	}

	protected OnTouchListener touchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			if (isLongClick) {

				switch (event.getAction()) {

				case MotionEvent.ACTION_DOWN:
					return false;

				case MotionEvent.ACTION_UP:

					if (isLongClick) {
						btn_voice.setBackgroundResource(R.drawable.chattxts);

						voice_rcd_hint_rcding.setVisibility(View.GONE);

						stop();

						isLongClick = false;

						endVoiceT = System.currentTimeMillis();

						voiceLong = endVoiceT - startVoiceT;

						time = (int) (voiceLong / 1000);

						L.i("time", time + "时长");

						if (time < 2) {
							isShosrt = true;
							voice_rcd_hint_loading.setVisibility(View.GONE);
							voice_rcd_hint_rcding.setVisibility(View.GONE);
							voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
							File file = new File(MainApplication.getInstance()
									.getAppVoiceDirectory() + "/" + voiceName);
							if (file.exists()) {
								file.delete();
							}

							mHandler.postDelayed(new Runnable() {
								public void run() {
									voice_rcd_hint_tooshort
											.setVisibility(View.GONE);
									rcChat_popup.setVisibility(View.GONE);
									isShosrt = false;
								}
							}, 300);
							return false;
						}
						// Log.i("上传文件", "上传文件");
						UploadVoice(voicePath);

						rcChat_popup.setVisibility(View.GONE);
					}

					break;

				}

			}

			return false;
		}
	};

	protected OnLongClickListener longClick = new OnLongClickListener() {

		@Override
		public boolean onLongClick(View v) {

			// Log.v("onLongClick", "开始录音");

			isLongClick = true;
			btn_voice.setBackgroundResource(R.drawable.chattxt2s);
			rcChat_popup.setVisibility(View.VISIBLE);
			voice_rcd_hint_loading.setVisibility(View.VISIBLE);
			voice_rcd_hint_rcding.setVisibility(View.GONE);
			voice_rcd_hint_tooshort.setVisibility(View.GONE);
			mHandler.postDelayed(new Runnable() {
				public void run() {
					if (!isShosrt) {
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.VISIBLE);
					}
				}
			}, 300);
			img1.setVisibility(View.VISIBLE);
			del_re.setVisibility(View.GONE);
			startVoiceT = System.currentTimeMillis();
			voiceName = myInfo.getUid() + "_" + System.currentTimeMillis()
					+ ".amr";
			start(voiceName);
			return true;
		}
	};

	private void UploadVoice(String fileSrc) {
		// TODO 自动生成的方法存根
		uploadFile = new File(fileSrc.trim());

		if (uploadFile.exists() && uploadFile.length() > 0) {

			final AsyncHttpClient client = new AsyncHttpClient();

			String contType = URLConnection.guessContentTypeFromName(fileSrc);

			RequestParams params = new RequestParams();

			try {
				params.put("args", getJsonArgs());
				params.put("attfile", uploadFile, contType);

				client.setTimeout(60);

				client.post(str_server + str_requestNameUpload, params,
						rpHandler);

			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}

	}

	private ResponseHandlerInterface rpHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBody) {

			try {
				String str_jsonReturn = new String(responseBody, "UTF-8");

				JsonParser parse = new JsonParser();

				jsonReturn = parse.parse(str_jsonReturn);

			} catch (Exception e) {

				L.e(e.getMessage());
			}

			UploadVoiceSuccess(time);
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] responseBody, Throwable error) {
			// TODO 自动生成的方法存根

		}
	};

	private String getJsonArgs() {

		if (myInfo != null) {

			Map<String, Object> validator = new HashMap<String, Object>();

			validator.put("uid", myInfo.getUid());
			validator.put("uname", myInfo.getUname());
			validator.put("pwd", myInfo.getPwd());
			validator.put("uguid", myInfo.getUguid());

			Map<String, Object> body = new HashMap<String, Object>();
			body.put("typeid", 2);
			body.put("filedatasrc", uploadFile.getPath());

			body.put("videolong", voiceLong);

			body.put("md5id", MyTools.getMd5ByFile(uploadFile));

			Map<String, Object> args = new HashMap<String, Object>();
			args.put("validator", validator);
			args.put("body", body);

			Gson gson = new Gson();
			String s = gson.toJson(args);

			return s;
		} else {
			return "";
		}
	}

	private void start(String name) {

		voicePath = MainApplication.getInstance().getAppVoiceDirectory() + "/"
				+ name;

		mSensor.start(voicePath);
		mHandler.postDelayed(mPollTask, POLL_INTERVAL);
	}

	private void stop() {

		mHandler.removeCallbacks(mPollTask);

		mSensor.stop();

		volume.setImageResource(R.drawable.amp1);
	}

	private Runnable mPollTask = new Runnable() {
		public void run() {
			double amp = mSensor.getAmplitude();
			updateDisplay(amp);
			mHandler.postDelayed(mPollTask, POLL_INTERVAL);
		}
	};

	private void updateDisplay(double signalEMA) {

		switch ((int) signalEMA) {
		case 0:
		case 1:
			volume.setImageResource(R.drawable.amp1);
			break;
		case 2:
		case 3:
			volume.setImageResource(R.drawable.amp2);

			break;
		case 4:
		case 5:
			volume.setImageResource(R.drawable.amp3);
			break;
		case 6:
		case 7:
			volume.setImageResource(R.drawable.amp4);
			break;
		case 8:
		case 9:
			volume.setImageResource(R.drawable.amp5);
			break;
		case 10:
		case 11:
			volume.setImageResource(R.drawable.amp6);
			break;
		default:
			volume.setImageResource(R.drawable.amp7);
			break;
		}
	}
}
